#include "HttpServer.hpp"
#include "protocol.hpp"
#include <iostream>
#include <memory>
#include "Util.hpp"

static void Usage(string str)
{
    cout << "Usage: " << str << " local_port" << endl;
}

enum
{
    DIV_ERR = 1,
    MOD_ERR,
    OP_ERR
};

std::string getType(const string &suffix)
{
    string type = "Content-Type: ";
    if (suffix == ".html")
        type += "text/html";
    else if (suffix == ".jpg")
        type += "application/x-jpg";

    //...
    type += "\r\n";
    return type;
}

// 1.服务器和网页分离，html
// 2.url文件路径中的/：web根目录
// 3.正确的给客户端返回正确的资源类型，依靠后缀映射资源类型
bool fun(const httpRequest &req, httpResponse &resp)
{
    std::cout << "-------------------http start------------" << std::endl;
    std::cout << req.inbuf << std::endl;
    std::cout << "method: " << req.method << std::endl;
    std::cout << "url: " << req.url << std::endl;
    std::cout << "httpVersion: " << req.httpVersion << std::endl;
    std::cout << "path: " << req.path << std::endl;
    std::cout << "suffix: " << req.suffix << std::endl;
    std::cout << "size: " << req.size << "字节" << std::endl;
    std::cout << "--------------------http end------------" << std::endl;

    resp.respLine = "http/1.1 200 OK\r\n";
    resp.respHeader = getType(req.suffix);
    if (req.size > 0)
    {
        resp.size = "Content-Lenght: ";
        resp.size += to_string(req.size);
        resp.size += "\r\n";
    }

    resp.respBlank = "\r\n";
    // resp.body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>for test</title><h1>Welcome</h1></head><body><p>若敢来犯</p></body></html>";
    resp.body;
    resp.body.resize(req.size + 1);
    if (!Util::readFile(req.path, (char *)resp.body.c_str(), req.size))
    {
        Util::readFile(html_404, (char *)resp.body.c_str(), req.size); // 说明路径不存在，设置路径为404
    }

    // 整合，最终发送的是outbuf
    resp.outbuf = resp.respLine;    // 响应行
    resp.outbuf += resp.respHeader; // 资源类型
    resp.outbuf += resp.size;
    resp.outbuf += resp.respBlank; // 空行
    resp.outbuf += resp.body;      // 响应正文
    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = atoi(argv[1]);
    unique_ptr<Server> svr(new Server(port, fun));
    svr->initServer();
    svr->start();

    return 0;
}
